<template>
<div class="usersAddorEdit">
    <form :model="data.formBook">
      <table>
        <tbody>
          <tr>
            <td><label for="">书名</label></td>
            <td><input type="text" placeholder="请输入书名" v-model="data.formBook.BookName"/></td>
          </tr>
          <tr>
            <td><label for="">作者</label></td>
            <td><input type="text" placeholder="请输入作者" v-model="data.formBook.author"/></td>
          </tr>
          <tr>
            <td><input type="button" value="保存" @click="saveBook" /></td>
            <td><input type="button" value="取消" /></td>
          </tr>
        </tbody>
      </table>
    </form>
  </div>

  <h1>用户信息管理</h1>
  <div>
    <div>
      <input type="text" placeholder="请输入关键词" v-model="data.keyword" />
      <input type="button" value="查询" @click="search" />
      <input type="button" value="新增" />
    </div>

    <table>
      <thead>
        <tr>
          <th>编号</th>
          <th>书名</th>
          <th>作者</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="book in data.books" :key="book.id">
          <td>{{ book.id }}</td>
          <td>{{ book.BookName }}</td>
          <td>{{ book.author }}</td>
          <td>
            <input type="button" @click="edit(book.id)" value="修改"/>
            <input type="button" @click="delet(book.id)" value="删除" />
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import axios from 'axios'
let data=reactive({
  books:[],
  keyword:'',
  formBook:{}

})
const api = 'http://localhost:3000'
function queryBooks() {
  console.log(data.keyword)
  axios.get(`${api}/bookList?keyword=${data.keyword}`).then((res) => {
    data.books = res.data
    console.log(data.books)
  })}
  function delet(id){
    axios.delete(`${api}/bookList/${id}`).then(()=>{
      queryBooks()
    })
  }
  function Add() {}
function search(){
  queryBooks()
}
function saveBook() {
  data.formBook.id ? updateBook(data.formBook.id) : addBook()
}
function updateBook(id) {
  axios.put(`${api}/bookList/${data.formBook.id}`, data.formBook).then(() => {
    queryBooks()
    data.formBook = {}
  })
}
queryBooks()


function addBook() {
  axios.post(`${api}/bookList`, data.formBook).then(() => {
    queryBooks()
    data.formBook = {}
  })
}

function edit(id) {
  axios.get(`${api}/bookList/${id}`).then((res) => {
    data.formBook = res.data
  })
}
</script>